<template>
  <div class="order-management">
    <el-card class="table-card">
      <el-table 
        :data="orders"
        v-loading="loading"
        style="width: 100%"
        stripe
      >
        <el-table-column prop="orderId" label="订单ID" width="100" align="center" />
        
        <el-table-column label="订单信息" min-width="220">
          <template #default="{ row }">
            <div class="order-info">
              <div class="order-number">订单号：{{ row.orderNumber }}</div>
              <div class="product-info">
             <el-image 
                  :src="'http://localhost:8092 '+  getFirstImage(row.images)"
                  style="width: 60px; height: 60px; margin-right: 10px"
                  fit="cover"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div>
                  <div class="product-name">{{ row.productName }}</div>
                  <div class="price">单价：¥{{ row.price }}</div>
                  <div class="quantity">数量：{{ row.quantity }}</div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="用户信息" width="180">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :src="'http://localhost:8092' +row.avatar" />
              <div class="user-meta">
                <div class="nickname">{{ row.nickname }}</div>
                <div class="user-id">用户ID: {{ row.userId }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="状态信息" width="200">
          <template #default="{ row }">
            <div class="status-group">
              <el-tag :type="statusTag(row.status)" effect="light">
                {{ formatStatus(row.status) }}
              </el-tag>
              <el-tag 
                v-if="row.afterSalesFlag !== 0"
                :type="afterSalesTag(row.afterSalesFlag)"
                style="margin-top: 5px"
              >
                {{ formatAfterSales(row.afterSalesFlag) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="时间信息" width="180">
          <template #default="{ row }">
            <div class="time-info">
              <div>创建：{{ formatTime(row.createdAt) }}</div>
              <div v-if="row.updatedAt">更新：{{ formatTime(row.updatedAt) }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <div class="actions">
              <el-button
                v-if="row.status === 2"
                type="primary"
                size="small"
                @click="handleShipment(row.orderId)"
              >
                确认发货
              </el-button>
              
              <el-popconfirm
                v-if="row.afterSalesFlag === 1"
                title="确定通过售后申请？"
                @confirm="handleAfterSales(row.orderId, true)"
              >
                <template #reference>
                  <el-button type="success" size="small" style="margin-top: 5px">
                    通过售后
                  </el-button>
                </template>
              </el-popconfirm>

              <el-popconfirm
                v-if="row.afterSalesFlag === 1"
                title="确定拒绝售后申请？"
                @confirm="handleAfterSales(row.orderId, false)"
              >
                <template #reference>
                  <el-button type="danger" size="small" style="margin-top: 5px">
                    拒绝售后
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const loading = ref(false)
const orders = ref([])

// 状态显示配置
const statusMap = {
  1: { text: '待付款', type: 'warning' },
  2: { text: '待发货', type: 'primary' },
  3: { text: '已发货', type: 'success' },
  4: { text: '已完成', type: 'info' },
  5: { text: '已取消', type: 'danger' }
}

const afterSalesMap = {
  0: { text: '无售后', type: 'info' },
  1: { text: '售后申请中', type: 'warning' },
  2: { text: '售后通过', type: 'success' },
  3: { text: '售后拒绝', type: 'danger' }
}
const getFirstImage = (images) => {
  if (!images) return '' // 处理 null 或 undefined
  const imageArray = images.split(',')
  return imageArray.length > 0 ? imageArray[0] : ''
}
// 初始化加载订单数据
const fetchOrders = async () => {
  try {
    loading.value = true
    const { data } = await axios.get('http://localhost:8092/order/list', {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (data.code === 200) {
      orders.value = data.data
    }
  } catch (error) {
    ElMessage.error('获取订单失败: ' + (error.response?.data?.msg || error.message))
  } finally {
    loading.value = false
  }
}

// 处理发货操作
const handleShipment = async (orderId) => {
  try {
    await axios.put('http://localhost:8092/order/confirmShipment', null, {
      params: { orderId },
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    ElMessage.success('发货操作成功')
    await fetchOrders()
  } catch (error) {
    ElMessage.error('操作失败: ' + (error.response?.data?.msg || error.message))
  }
}

// 处理售后操作
const handleAfterSales = async (orderId, approve) => {
  try {
    const params = { orderId, approve }
    if (!approve) params.rejectReason = '不符合售后政策'
    
    await axios.put('http://localhost:8092/order/processAfterSales', null, {
      params,
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    ElMessage.success(`已${approve ? '通过' : '拒绝'}售后申请`)
    await fetchOrders()
  } catch (error) {
    ElMessage.error('操作失败: ' + (error.response?.data?.msg || error.message))
  }
}

// 格式化时间显示
const formatTime = (dateStr) => {
  return new Date(dateStr).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 状态标签类型
const statusTag = (status) => statusMap[status]?.type || 'info'
const afterSalesTag = (flag) => afterSalesMap[flag]?.type || 'info'

// 状态文本显示
const formatStatus = (status) => statusMap[status]?.text || '未知状态'
const formatAfterSales = (flag) => afterSalesMap[flag]?.text || '未知状态'

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.order-management {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.table-card {
  margin-top: 15px;
  :deep(.el-card__body) {
    padding: 10px;
  }
}
.image-error {
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}
.user-info {
  display: flex;
  align-items: center;
  .el-avatar {
    width: 36px;
    height: 36px;
    margin-right: 10px;
  }
  .user-meta {
    line-height: 1.4;
    .nickname {
      font-size: 13px;
      color: #333;
    }
    .user-id {
      font-size: 12px;
      color: #999;
    }
  }
}

.order-info {
  .order-number {
    font-size: 12px;
    color: #666;
    margin-bottom: 8px;
  }
  .product-info {
    display: flex;
    align-items: center;
    .product-name {
      font-size: 14px;
      margin-bottom: 4px;
    }
    .price, .quantity {
      font-size: 12px;
      color: #999;
    }
  }
}

.status-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.time-info {
  font-size: 12px;
  color: #666;
  line-height: 1.6;
}

.actions {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.el-table {
  :deep(th.el-table__cell) {
    background-color: #f8f9fa;
  }
  :deep(.el-table__cell) {
    padding: 12px 0;
  }
}
</style>